import * as itf from "./itf";

export class ORDER {
  // 公共
  money: itf.ns = 0; // 交易金额 单位为【分】
  title: string = ""; // 商品名称
  order: string = ""; // 商户订单号
  backUrl?: string; // 后台通知地址
  realPay?: itf.fun; // 创建订单时可选参数.支付成功后将执行此函数.传递参数为REQUEST类型

  [prop: string]: any;

  // 银联
  txnTime?: string;
  payTimeout?: string;
  accessType?: string; // "0" | "1" | "3"; // 0：商户直连接入;1：收单机构接入;2：平台商户接入
  frontUrl?: string; // 前台通知地址
  channelType?: string; // "07" | "08"; // 渠道类型，07-PC，08-手机
  txnSubType?: string; // 01：自助消费，通过地址的方式区分前台消费和后台消费（含无跳转支付） 03：分期付款
  // 微信
  ip?: string; // 特殊网络环境
  tradeType?: string; // 支付类型 默认:NATIVE
  openid?: string; // 用户openid
  orderT?: string; // 退款订单号
  orderM?: itf.ns; // 退款时填写 订单原金额.留空则查询.

  constructor (param: itf.oa) {
    Object.assign(this, param);
    this.money = param.money ? param.money : 0;
    this.title = param.title ? param.title.toString() : "   ";
  }
}
export class REQUEST {
  order: string = ""; // 商户订单号
  payment: number = 0; // 金额,单位分
  queryId?: string; // 流水号.退款时要用这操蛋玩意
  url?: string;
  body?: string;
  readonly err?: any;
  check: boolean = false;
  raw: any; // 原始返回数据
  [k: string]: any;
  constructor (p: any) {
    if (p instanceof REQUEST) {
      Object.assign(this, p);
      return;
    }
    if (!p) p = { err: "数据为空", raw: p };
    this.order = p.order || p.orderId || p.out_trade_no || "";

    if (typeof p.queryId == "string") this.queryId = p.queryId;
    if (p.err) {
      this.err = p.err;
      const t = Object.assign({}, p);
      delete t.err;
      this.raw = t.raw ? t.raw : t;
    } else {
      if (typeof p.code_url == "string" || typeof p.url == "string") this.url = p.url || p.code_url;
      this.check =
        p.respCode == "00" ||
        p.result_code == "SUCCESS" ||
        p.err_code_des == "订单已全额退款" ||
        p.refund_status == "SUCCESS" ||
        p.trade_status == "TRADE_SUCCESS" || // 支付宝
        p.msg == "Success" ||
        p.sub_code == "ACQ.TRADE_HAS_CLOSE" ||
        false;
      if (this.check) {
        this.payment = p.money || p.settleAmt || p.cash_fee || p.total_fee ||
          this.toNumber(p.total_amount, 100) || this.toNumber(p.refund_fee, 100) ||
          p.txnAmt ||
          0;
        this.payment = this.toNumber(this.payment);
        if (typeof p.body == "string") this.body = p.body;
        if (typeof p.app) this.app = p.app;
      } else this.err = "订单未完成";
      this.raw = p;
    }
  }
  private toNumber(p: any, multiple: number = 1) {
    let r = Number(p);
    r = r ? r : 0;
    return parseInt((r * multiple).toString());
  }
}